package controller;

import databaseLayer.MoviesLookUp;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import movieBean.Movie;
import userBean.UserIdentity;

/**
 *
 * @author Sam
 */
public class ManagerIndex extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String address = "/management.jsp";
        
        HttpSession session = request.getSession();
        if (session.isNew() || !(((UserIdentity)session.getAttribute("userIdentity")).getUserType().equals("TicketingManager"))) {
            if (session.isNew()) {
                session.invalidate();
            }
            
            address = "index.do";
        }
        else {
            Movie[] availableMovies;
            Date currentTime = new Date();
            SimpleDateFormat timeZoneFormatter = new SimpleDateFormat("z");
            String timeZone = timeZoneFormatter.format(currentTime);

            String initialTime = "0000/00/00 00:00:00 " + timeZone;
            String endTime = "9999/99/99 23:59:59 " + timeZone;
            availableMovies = MoviesLookUp.getAllMovies(initialTime, endTime);

            String topDisplayMsg = (String)session.getAttribute("topDisplayMsg");
            if (topDisplayMsg == null || topDisplayMsg == "") {
                topDisplayMsg = "";
            }
            else {
                session.removeAttribute("topDisplayMsg");
            }

            request.setAttribute("availableMovies", availableMovies);
            request.setAttribute("topDisplayMsg", topDisplayMsg);

            int noOfMovie = availableMovies.length;
            request.setAttribute("noOfMovie", noOfMovie);
        }
        
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
